package com.chainyoung.component_tmtrade.ui.fragment.c2c;


import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chainyoung.common.appcommon.entity.CommonList;
import com.chainyoung.common.appcommon.entity.TradeParams;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.bean.ReqModel;
import com.chainyoung.common.constant.CommonStringConstants;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.http.JsonConventUtils;
import com.chainyoung.common.http.websocket.WebSoketUtils;
import com.chainyoung.common.http.websocket.WsManager;
import com.chainyoung.common.http.websocket.WsStatus;
import com.chainyoung.common.http.websocket.WsStatusListener;
import com.chainyoung.common.utils.CommonUtil;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.common.view.ActionSheetDialog;
import com.chainyoung.common.view.NoScrollListView;
import com.chainyoung.common.view.kprogresshud.KProgressHUD;
import com.chainyoung.component_tmtrade.R;
import com.chainyoung.component_tmtrade.R2;
import com.chainyoung.component_tmtrade.bean.MyBanlance;
import com.chainyoung.component_tmtrade.bean.TradeCurrencyItem;
import com.chainyoung.component_tmtrade.bean.TradeCurrentDetail;
import com.chainyoung.component_tmtrade.bean.TradeCurrentTotal;
import com.chainyoung.component_tmtrade.di.component.DaggerTradeCurrencyComponent;
import com.chainyoung.component_tmtrade.di.module.TradeCurrencyModule;
import com.chainyoung.component_tmtrade.ui.activity.TradeCurrencyMarketListActivity;
import com.chainyoung.component_tmtrade.ui.activity.TradeCurrencyRecordActivity;
import com.chainyoung.component_tmtrade.ui.adapter.TradeAgencyAdapter;
import com.chainyoung.component_tmtrade.ui.adapter.TradeCurrency2CurrencyAdapter;
import com.chainyoung.component_tmtrade.ui.mvp.contract.TradeCurrencyBuyContract;
import com.chainyoung.component_tmtrade.ui.mvp.presenter.TradeCurrencyBuyPresenter;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;

import org.simple.eventbus.Subscriber;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Response;
import okio.ByteString;
import q.rorbin.badgeview.QBadgeView;

import static android.app.Activity.RESULT_OK;
import static com.chainyoung.router.RouterConstants.PATH_TRADE_CURRENCY;

@Route(path = PATH_TRADE_CURRENCY)
public class TradeCoin2CoinFragment extends BaseFragment<TradeCurrencyBuyPresenter> implements TradeCurrencyBuyContract.View {

    @BindView(R2.id.cl)
    CoordinatorLayout cl;
    @BindView(R2.id.appbar_layout)
    AppBarLayout appbar_layout;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.rv_list)
    SwipeMenuRecyclerView rvList;//委托记录列表
    @BindView(R2.id.rg)
    RadioGroup radioGroup;
    @BindView(R2.id.rb_buy_in)
    RadioButton rbBuyIn;
    @BindView(R2.id.rb_sell_out)
    RadioButton rbSellOut;
    @BindView(R2.id.list_view_sell)
    NoScrollListView lvSell;//卖深度图
    @BindView(R2.id.list_view_buy)
    NoScrollListView lvBuy;//买深度图
    @BindView(R2.id.et_trade_num)
    EditText etTradeNum;//买入/卖出数量
    @BindView(R2.id.tv_buy)
    TextView tvBuy;//确认买卖按钮
    @BindView(R2.id.tv_total_amount)
    TextView tvTotalAmount;//交易额
    @BindView(R2.id.tv_newest_price)
    TextView tvNewestPrice;//实时最新价
    @BindView(R2.id.et_price)
    EditText etPrice;//输入交易价格
    @BindView(R2.id.tv_price_type)
    TextView tvPriceType;///交易价格类型（以交易区为单位）
    @BindView(R2.id.tv_num_type)
    TextView tvNumType;//交易数量类型（以交易市场为单位）
    @BindView(R2.id.tv_available_num)
    TextView tvAvailableNum;//可用当前交易市场币种数量 区分买卖
    @BindView(R2.id.tv_total_type)
    TextView tvTotalType;//交易额类型
    @BindView(R2.id.tv_price_cny)
    TextView tvPriceCny;//人民币价格


    /**
     * 委托记录
     */
    private TradeAgencyAdapter mAdapter;
    private List<TradeCurrencyItem> mData = new ArrayList<>();
    private boolean isCanloadMore;
    protected int pageNo = 1;


    /**
     * websocket
     */
    private WsManager wsManager;
    private WsStatusListener wsStatusListener;

    /**
     * wbsocket 返回买卖实时数据
     */
    private List<TradeCurrentDetail> tradeBuyList = new ArrayList<>();
    private List<TradeCurrentDetail> tradeSellList = new ArrayList<>();
    private TradeCurrency2CurrencyAdapter mBuyAdapter;

    private TradeCurrency2CurrencyAdapter mSellAdapter;

    private int removedPosition;

    /**
     * 币币交易对
     */
    private String coinTypeIn = "ETH", coinTypeOut = "CBOB";
    private String currentTitle = "ETH/CBOB";//后面为交易区，前面为交易市场
    private String market;//例btc_bit

    /**
     * websocket 订阅参数topic
     */
    private String topicName;

    /**
     * 当前最新价 由websocket 返回
     */
    private String newestPrice = "";


    /**
     * 区分买卖
     */
    private static final int TYPE_BUY = 1;
    private static final int TYPE_SELL = 2;
    private static final int TYPE_ALL = 0;

    private int tradeType = TYPE_BUY;//交易类型
    private int recordType = TYPE_ALL;//委托列表类型

    /**
     * 资产
     */
    private String coinTypeInNum = "";//拥有的要交易的市场币种数量
    private String coinTypeOutNum = "";//拥有的交易区币种数量

    /**
     * 是否初次取得最新价
     */
    private boolean isFirstSetPrice = true;
    private boolean isReselectPrice = false;

    /**
     * 消息角标
     */
    private QBadgeView badgeView;

    /**
     * @param
     */
    private String rateCny;//市场币对rmb汇率

    //   -----------------------------------------------初始化--------------------------------------------------------------------------
    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerTradeCurrencyComponent.builder()
                .appComponent(appComponent)
                .tradeCurrencyModule(new TradeCurrencyModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initUi() {
        super.initUi();
        mCurrentTtile.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0, R.mipmap.icon_select_trade_down, 0);
        showAndSetBarRightIcon(R.mipmap.ic_kline);
        // showAndSetBarRightLeftIcon(R.mipmap.ic_kline);
        getMarketName();
        initMsg();
        initListener();
        initView();
        initLists();
        initRv();
        initWs();
    }

    private void initMsg() {
        int num = 0;
        if (CommonUtil.getUserInfo() != null) {
            num = CommonUtil.getUserInfo().getUnread_msg_num();
        }
       /* if (badgeView == null) {
            badgeView = new QBadgeView(mContext);
            badgeView.setBadgeBackgroundColor(ContextCompat.getColor(mContext, R.color._F95A54));
            badgeView.setBadgeTextColor(ContextCompat.getColor(mContext, R.color.white));
            badgeView.setBadgeTextSize(9, true);
            badgeView.bindTarget(mBarRightImageView).setBadgeGravity(Gravity.TOP | Gravity.END).
                    setGravityOffset(4, 3, true).
                    setBadgeNumber(num);
        } else {
            badgeView.setBadgeNumber(num);
        }*/
    }

    private void initView() {
        tvPriceType.setText(getString(R.string.price) + "(" + coinTypeOut + ")");
        tvNumType.setText(coinTypeIn);
        tvTotalType.setText(String.format(mContext.getString(R.string.tmtrade_total_type), coinTypeOut));
        etPrice.clearFocus();
        etTradeNum.clearFocus();
        etPrice.setHint(tradeType == TYPE_BUY ? "买入价格" : "卖出价格");
        tvBuy.setText(tradeType == TYPE_BUY ? getString(R.string.buy_in) + "(" + coinTypeIn + ")" : getString(R.string.sell_out) + "(" + coinTypeIn + ")");
        tvBuy.setBackgroundResource(tradeType == TYPE_BUY ? R.drawable.shape_green_radius_8 : R.drawable.shape_red_radius_8);
        if (mData.isEmpty()) {
//            rvList.setNestedScrollingEnabled(false);
//            cl.setNestedScrollingEnabled(false);
//            cl.setOverScrollMode(OVER_SCROLL_IF_CONTENT_SCROLLS);
//            refreshLayout.setNestedScrollingEnabled(false);
//            appbar_layout.setNestedScrollingEnabled(false);


        }
    }

    private void initListener() {
        etPrice.addTextChangedListener(new TextWatcher() {
            boolean deleteLastChar;// 是否需要删除末尾

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    // 如果点后面有超过6位数值,则删掉最后一位
                    int length = s.length() - s.toString().lastIndexOf(".");
                    // 说明后面有6位数值
                    deleteLastChar = length >= 8;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s == null) {
                    return;
                }
                if (deleteLastChar) {
                    // 设置新的截取的字符串
                    etPrice.setText(s.toString().substring(0, s.toString().length() - 1));
                    // 光标强制到末尾
                    etPrice.setSelection(etPrice.getText().length());
                }
                // 以小数点开头，前面自动加上 "0"
                if (s.toString().startsWith(".")) {
                    etPrice.setText("0" + s);
                    //etPrice.setSelection(etPrice.getText().length());
                }
                if (s.toString().startsWith("0") && (s.toString().length() > 1) && !s.toString().startsWith("0.")) {
                    etPrice.setText(s.toString().substring(1));
                    // etPrice.setSelection(etPrice.getText().length());
                }

                countTotal();
            }
        });

        etTradeNum.addTextChangedListener(new TextWatcher() {
            boolean deleteLastChar;// 是否需要删除末尾

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    // 如果点后面有超过6位数值,则删掉最后一位
                    int length = s.length() - s.toString().lastIndexOf(".");
                    // 说明后面有6位数值
                    deleteLastChar = length >= 8;
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s == null) {
                    return;
                }
                if (deleteLastChar) {
                    // 设置新的截取的字符串
                    etTradeNum.setText(s.toString().substring(0, s.toString().length() - 1));
                    // 光标强制到末尾
                    // etTradeNum.setSelection(etTradeNum.getText().length());
                }
                // 以小数点开头，前面自动加上 "0"
                if (s.toString().startsWith(".")) {
                    etTradeNum.setText("0" + s);
                    // etTradeNum.setSelection(etTradeNum.getText().length());
                }
                if (s.toString().startsWith("0") && (s.toString().length() > 1) && !s.toString().startsWith("0.")) {
                    etTradeNum.setText(s.toString().substring(1));

                }

                countTotal();
            }
        });

    }

    /**
     * 计算交易额
     */
    private void countTotal() {
        if (!StringUtil.viewGetTextIsEmpty(etPrice)) {
            tvPriceCny.setText("≈CNY " + new BigDecimal(rateCny).multiply(new BigDecimal(StringUtil.viewGetText(etPrice))).setScale(2, RoundingMode.DOWN).toPlainString());
        }else {
            tvPriceCny.setText("");
        }

        if (StringUtil.viewGetTextIsEmpty(etPrice) || StringUtil.viewGetTextIsEmpty(etTradeNum)) {
            tvTotalAmount.setText("0");
            return;
        }
        BigDecimal bd1 = new BigDecimal(StringUtil.viewGetText(etPrice));
        BigDecimal bd2 = new BigDecimal(StringUtil.viewGetText(etTradeNum));
        tvTotalAmount.setText(String.valueOf(bd1.multiply(bd2).setScale(6, BigDecimal.ROUND_DOWN)));

    }


    private void initLists() {
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_buy_in) {
                    tradeType = TYPE_BUY;
                } else {
                    tradeType = TYPE_SELL;
                }
                updateTradeType();
            }
        });


        mBuyAdapter = new TradeCurrency2CurrencyAdapter(mContext, tradeBuyList, TYPE_BUY);
        mSellAdapter = new TradeCurrency2CurrencyAdapter(mContext, tradeSellList, TYPE_SELL);
        lvSell.setAdapter(mSellAdapter);
        lvBuy.setAdapter(mBuyAdapter);
    }

    private void initRv() {
        rvList.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new TradeAgencyAdapter(mData);
//        DividerItemDecoration itemDecoration=new DividerItemDecoration(mContext,DividerItemDecoration.VERTICAL);
//        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext,R.drawable.shape_divider_gray_10));
//        rvList.addItemDecoration(itemDecoration);
        rvList.setSwipeMenuCreator(mSwipeMenuCreator);
        rvList.setSwipeMenuItemClickListener(mMenuItemClickListener);
        rvList.setAdapter(mAdapter);
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isCanloadMore) {
                    pageNo++;
                    getExchangeList();
                } else {
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                getExchangeList();
            }
        });

    }

    SwipeMenuCreator mSwipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu leftMenu, SwipeMenu rightMenu, int viewType) {

            int width = getResources().getDimensionPixelSize(R.dimen.dp_70);
            int height = ViewGroup.LayoutParams.MATCH_PARENT;

            SwipeMenuItem deleteItem = new SwipeMenuItem(mContext)
                    .setText(getString(R.string.tmtrade_cancel))
                    .setBackgroundColorResource(R.color._F95A54)
                    .setTextColorResource(R.color.white)
                    .setWidth(width)
                    .setHeight(height);
            rightMenu.addMenuItem(deleteItem); // 在Item右侧添加一个菜单。

        }
    };

    SwipeMenuItemClickListener mMenuItemClickListener = new SwipeMenuItemClickListener() {
        @Override
        public void onItemClick(SwipeMenuBridge menuBridge) {
            // 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱。
            menuBridge.closeMenu();
            int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
            final int adapterPosition = menuBridge.getAdapterPosition(); // RecyclerView的Item的position。
            int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。
            removedPosition = adapterPosition;
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setMessage(R.string.tmtrade_confirm_cancel_exchange)
                    .setPositiveButton(mContext.getString(R.string.confirm), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            TreeMap<String, Object> map = new TreeMap<>();
                            map.put("token", SPUtil.getString(LibConstant.TOKEN));
                            map.put("id", mAdapter.getItem(adapterPosition).getId());
                            mPresenter.cancelExchange(map);
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton(mContext.getString(R.string.cancel), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            builder.create();
            builder.show();


        }
    };


    private void initWs() {
        wsManager = WebSoketUtils.getWsManager();
        wsStatusListener = new WsStatusListener() {
            @Override
            public void onMessage(ByteString bytes) {
                super.onMessage(bytes);
                String r = JsonConventUtils.byteBufferToString(bytes.asByteBuffer());
                try {
                    String result = JsonConventUtils.uncompress(r);
                    handleResult(result);
                    // Log.d(TAG, result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // EventBus.getDefault().post(new BaseEvent<>(BaseEvent.EventCode.WS_TRADE_OPEN));
            }

            @Override
            public void onFailure(Throwable t, Response response) {
                super.onFailure(t, response);
            }

            @Override
            public void onOpen(Response response) {
                super.onOpen(response);
//                if (isVisiable) {
//                    getMarketList();
//                }
                getMarketList();
                //EventBus.getDefault().post(new BaseEvent<>(BaseEvent.EventCode.WS_TRADE_OPEN));
            }
        };
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void onFirstUserVisible() {
        wsManager.startConnect();
        wsManager.setWsStatusListener(wsStatusListener);
        refreshData();

    }

    @Override
    public void onUserVisible() {
        super.onUserVisible();
        if (wsManager.getCurrentStatus() != WsStatus.CONNECTED) {
            wsManager.startConnect();
            wsManager.setWsStatusListener(wsStatusListener);
        } else {
            getMarketList();
        }
        refreshData();
    }

    @Override
    public void onUserInvisible() {
        super.onUserInvisible();
        wsManager.stopConnect();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmtrade_fragment_trade_c2c_new;
    }


    //-------------------------------------------------------UI变更-----------------------------------------------------------

    /**
     * 切换买卖
     */
    private void updateTradeType() {
        etTradeNum.setHint(tradeType == TYPE_BUY ? R.string.tmtrade_buy_in_num : R.string.tmtrade_sell_out_num);
        etPrice.setHint(tradeType == TYPE_BUY ? "买入价格" : "卖出价格");
        tvPriceCny.setText("");
        tvBuy.setText(tradeType == TYPE_BUY ? getString(R.string.buy_in) + "(" + coinTypeIn + ")" : getString(R.string.sell_out) + "(" + coinTypeIn + ")");
        tvBuy.setBackgroundResource(tradeType == TYPE_BUY ? R.drawable.shape_green_radius_8 : R.drawable.shape_red_radius_8);
        tvTotalAmount.setTextColor(tradeType == TYPE_BUY ? ContextCompat.getColor(mContext, R.color._09C173) : ContextCompat.getColor(mContext, R.color._F95A54));
        tvAvailableNum.setText(tradeType == TYPE_BUY ?
                String.format(getString(R.string.tmtrade_can_use), coinTypeOut, coinTypeOutNum) : String.format(getString(R.string.tmtrade_can_use), coinTypeIn, coinTypeInNum));
        etTradeNum.setText("");
    }

    /**
     * 切换交易区
     */
    private void updateCoinType() {
        tvPriceType.setText(String.format("%s(%s)", getString(R.string.price), coinTypeOut));
        tvNumType.setText(coinTypeIn);
        // txtPrice.setText(String.format(mContext.getString(R.string.tmtrade_price_bit), coinTypeOut));
        // txtAmount.setText(String.format(mContext.getString(R.string.tmtrade_amount_bit), coinTypeIn));
        tvTotalType.setText(String.format(mContext.getString(R.string.tmtrade_total_type), coinTypeOut));
        etPrice.clearFocus();
        etTradeNum.clearFocus();
        tvBuy.setText(tradeType == TYPE_BUY ? getString(R.string.buy_in) + "(" + coinTypeIn + ")" : getString(R.string.sell_out) + "(" + coinTypeIn + ")");
        tvBuy.setBackgroundResource(tradeType == TYPE_BUY ? R.drawable.shape_green_radius_8 : R.drawable.shape_red_radius_8);
        etTradeNum.setText("");
        tvTotalAmount.setText("0");
    }


    /**
     * 切换委托列表类型
     */


    /**
     * 解析市场名 并刷新请求
     */
    private void getMarketName() {
        setCurrentTitle(currentTitle);
        String[] coinTypes = currentTitle.split("/");
        try {
            coinTypeIn = coinTypes[0];
            coinTypeOut = coinTypes[1];
            market = coinTypeIn.toLowerCase() + "_" + coinTypeOut.toLowerCase();
            topicName = "market." + market + ".depth.5.fill";
            updateCoinType();
            getMarketList();
        } catch (Exception ignored) {

        }
        List<String> coinTypeList = new ArrayList<>();
        coinTypeList.add(coinTypeIn);
        coinTypeList.add(coinTypeOut);
        //通知下级页面更新
        //  EventBus.getDefault().post(new BaseEvent<>(BaseEvent.EventCode.REFRESH_MARKET_COUPLE_NAME, coinTypeList));

    }


    //    ---------------------------------------------------点击事件-------------------------------------------------------------------


    @Override
    public void onRightImgClicked(View v) {
        super.onRightImgClicked(v);
        RouterUtils.getInstance()
                .build(RouterConstants.PATH_MARKET_KLINE)
                .withString(CommonStringConstants.CURRENCY_IN, coinTypeIn)
                .withString(CommonStringConstants.CURRENCY_OUT, coinTypeOut)
                .navigation(mContext);
        /*RouterUtils.getInstance()
                .build(RouterConstants.PATH_MESSAGE_CENTER)
                .navigation();*/
    }

    @Override
    public void onRightLeftImgClicked(View v) {
        super.onRightLeftImgClicked(v);
        /*RouterUtils.getInstance()
                .build(RouterConstants.PATH_MARKET_KLINE)
                .withString(CommonStringConstants.CURRENCY_IN, coinTypeIn)
                .withString(CommonStringConstants.CURRENCY_OUT, coinTypeOut)
                .navigation(mContext);*/
    }

    /**
     * 切换交易对
     */
    private static final int REQUEST_MARKET = 0x111;

    @OnClick(R2.id.title)
    void selectMarket() {
        Intent intent = new Intent(mContext, TradeCurrencyMarketListActivity.class);
        intent.putExtra("isFromPurse", false);
        startActivityForResult(intent, REQUEST_MARKET);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (!currentTitle.equals(data.getStringExtra("marketName"))) {
            tradeBuyList.clear();
            tradeSellList.clear();
        }
        currentTitle = data.getStringExtra("marketName");
        isReselectPrice = true;
        getMarketName();
        pageNo = 1;
        getExchangeList();
        getMyBalance();
        clearMarketData();
    }

    /**
     * 清除之前交易市场数据
     */
    private void clearMarketData() {
        tradeSellList.clear();
        tradeBuyList.clear();
        for (int i = 0; i < 5; i++) {
            TradeCurrentDetail item = new TradeCurrentDetail();
            tradeBuyList.add(item);
            tradeSellList.add(item);
        }
        mBuyAdapter.notifyDataSetChanged();
        mSellAdapter.notifyDataSetChanged();
        tvNewestPrice.setText("0.000000");
    }

    /**
     * 自动填充当前最新价
     */
    @OnClick(R2.id.tv_newest_price)
    void setPrice() {
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.anim_scale_big);
        animation.setDuration(100);
        etPrice.startAnimation(animation);
        etPrice.setText(tvNewestPrice.getText().toString().trim());
        //etPrice.setSelection(etPrice.getText().toString().length());
    }

    /**
     * 自动以最后一位加1
     */
    @OnClick(R2.id.iv_add)
    void add() {
        String s = etPrice.getText().toString();
        if (TextUtils.isEmpty(s)) {
            return;
        }
        int length = 0;
        if (s.contains(".")) {
            length = s.length() - s.lastIndexOf(".") - 1;
        }
        long oldPrice = new BigDecimal(s).multiply(new BigDecimal(10).pow(length)).longValue();
        oldPrice++;
        etPrice.setText(new BigDecimal(oldPrice).divide(new BigDecimal(10).pow(length)).setScale(length, BigDecimal.ROUND_DOWN).toString());
        etPrice.setSelection(etPrice.getText().toString().length());
    }

    /**
     * 自动以最后一位减1
     */
    @OnClick(R2.id.iv_sub)
    void sub() {
        String s = etPrice.getText().toString();
        if (TextUtils.isEmpty(s) || new BigDecimal(s).compareTo(BigDecimal.ZERO) == 0) {
            return;
        }
        int length = 0;
        if (s.contains(".")) {
            length = s.length() - s.lastIndexOf(".") - 1;
        }
        long oldPrice = new BigDecimal(s).multiply(new BigDecimal(10).pow(length)).longValue();
        oldPrice--;
        etPrice.setText(new BigDecimal(oldPrice).divide(new BigDecimal(10).pow(length)).setScale(length, BigDecimal.ROUND_DOWN).toString());
        etPrice.setSelection(etPrice.getText().toString().length());
    }

    /**
     * 确认交易
     */
    @OnClick(R2.id.tv_buy)
    void confirmBuy() {


        if (StringUtil.viewGetTextIsEmpty(etPrice)) {
            ToastUtil.showToast(tradeType == TYPE_BUY ? R.string.pls_input_buy_price : R.string.pls_input_sell_price);
            return;
        }
        if (StringUtil.viewGetTextIsEmpty(etTradeNum)) {
            ToastUtil.showToast(tradeType == TYPE_BUY ? R.string.pls_input_buy_amount : R.string.pls_input_sell_amount);
            return;
        }
        if (new BigDecimal(etPrice.getText().toString()).compareTo(BigDecimal.ZERO) == 0) {
            ToastUtil.showToast(getString(R.string.tmtrade_pls_input_correct_price));
            return;
        }
        if (new BigDecimal(etTradeNum.getText().toString()).compareTo(BigDecimal.ZERO) == 0) {
            ToastUtil.showToast(getString(R.string.tmtrade_input_correct_num));
            return;
        }

        TreeMap<String, Object> map = new TreeMap<>();
        map.put("type", tradeType);
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("market", market);
        map.put("num", StringUtil.viewGetText(etTradeNum));
        map.put("price", StringUtil.viewGetText(etPrice));
        mPresenter.addExchange(map, getString(R.string.tmtrade_trade_in_progress));

    }


    /**
     * 查看成交记录
     */

    @OnClick(R2.id.tv_check_record)
    void onCheckRecord() {
        Intent intent = new Intent(mContext, TradeCurrencyRecordActivity.class);
        intent.putExtra("coinTypeIn", coinTypeIn);
        intent.putExtra("coinTypeOut", coinTypeOut);
        mContext.startActivity(intent);
    }


 /*   @OnClick(R2.id.txt_type)
    void selectRecordType() {
        new ActionSheetDialog(mContext).builder().setCancelable(true).setCanceledOnTouchOutside(true).
                addSheetItem("看全部", ActionSheetDialog.SheetItemColor.Blue, new ActionSheetDialog.OnSheetItemClickListener() {
                    @Override
                    public void onClick(int which) {
                        recordType = TYPE_ALL;
                      //  txtType.setText(R.string.tmtrade_all);
                        pageNo = 1;
                        getExchangeList();
                    }
                }).addSheetItem("只看买入", ActionSheetDialog.SheetItemColor.Blue, new ActionSheetDialog.OnSheetItemClickListener() {
            @Override
            public void onClick(int which) {
                recordType = TYPE_BUY;
               // txtType.setText(R.string.buy_in);
                pageNo = 1;
                getExchangeList();
            }
        }).addSheetItem("只看卖出", ActionSheetDialog.SheetItemColor.Blue, new ActionSheetDialog.OnSheetItemClickListener() {
            @Override
            public void onClick(int which) {
                recordType = TYPE_SELL;
               // txtType.setText(R.string.sell_out);
                pageNo = 1;
                getExchangeList();
            }
        })
                .show();
    }*/


    //---------------------------------------------------Http 获取资产和进行交易-------------------------------------------------------------------

    /**
     * 刷新数据
     */
    private void refreshData() {
        getMyBalance();
        pageNo = 1;
        getExchangeList();
    }


    /**
     * 获取资产
     */
    private void getMyBalance() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("market", market);
        mPresenter.getMyBalance(map);
    }

    @Override
    public void onGetCoinBalance(MyBanlance data) {
        coinTypeOutNum = data.getScb();
        coinTypeInNum = data.getXnb();
        tvAvailableNum.setText(tradeType == TYPE_BUY ?
                String.format(getString(R.string.tmtrade_can_use), coinTypeOut, coinTypeOutNum) : String.format(getString(R.string.tmtrade_can_use), coinTypeIn, coinTypeInNum));
    }


    /**
     * 提交交易
     */
    @Override
    public void onAddExchangeSuccess(Object object) {
        KProgressHUD.create(mContext)
                .setCustomView(mContext, R.drawable.tips_correct)
                .setLabel(getString(R.string.apply_trade_success))
                .show().setDuration(1500);
        etPrice.setText(tvNewestPrice.getText().toString());
        etTradeNum.setText("");
        tvTotalAmount.setText("0");
        refreshData();
    }

    /**
     * 取消交易
     */
    @Override
    public void onCancelTradeSuccess(Object object) {
        KProgressHUD.create(mContext)
                .setCustomView(mContext, R.drawable.tips_correct)
                .setLabel(getString(R.string.apply_trade_canceled))
                .show().setDuration(1500);
        mData.remove(removedPosition);
        mAdapter.notifyItemRemoved(removedPosition);
        mAdapter.notifyItemRangeChanged(removedPosition, mData.size());
    }


    //    ---------------------------------------------------Http请求委托记录------------------------------------------------------------------------

    /**
     * 获取委托记录
     */
    private void getExchangeList() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        map.put("market", market);
        map.put("type", recordType);
        map.put("list_type", "curr");
        map.put("page", pageNo);
        map.put("limit", LibConstant.PAGE_SIZ);
        map.put("get_all_history", false);
        map.put("orderno", "");
        mPresenter.getExchangeList(map);
    }


    @Override
    public void onGetTradeListSuccess(CommonList<TradeCurrencyItem> data) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (pageNo == 1) {
            mData.clear();
        }
        if (data == null) {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
            // loadService.showCallback(EmptyCallback.class);
            //rlEmpty.setVisibility(View.VISIBLE);
            //rvList.setVisibility(View.GONE);
            mAdapter.notifyDataSetChanged();
            return;
        }
        if (!data.getList().isEmpty()) {
            mData.addAll(data.getList());
            if (data.getList().size() < LibConstant.PAGE_SIZ) {
                isCanloadMore = false;
                refreshLayout.setEnableLoadMore(false);
            } else {
                isCanloadMore = true;
                refreshLayout.setEnableLoadMore(true);
            }
        }

        if (mData.isEmpty()) {

//            loadService.showCallback(EmptyCallback.class);
            //  rlEmpty.setVisibility(View.VISIBLE);
            //  rvList.setVisibility(View.GONE);
        } else {

//            loadService.showSuccess();
            //  rlEmpty.setVisibility(View.GONE);
            //rvList.setVisibility(View.VISIBLE);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onGetTradeListFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();

        //   rlEmpty.setVisibility(View.VISIBLE);
        // rvList.setVisibility(View.GONE);
        //  loadService.showCallback(RetryCallback.class);
    }


    //   ----------------------------------------------------WebSocket实时请求-----------------------------------------------------------------------

    /**
     * 订阅和请求websocket
     */
    public void getMarketList() {
        ReqModel reqModel = new ReqModel();
        reqModel.setType("sub");
        reqModel.setTopic(topicName);
        wsManager.sendMessage(new Gson().toJson(reqModel));

        ReqModel reqModel1 = new ReqModel();
        reqModel1.setType("req");
        reqModel1.setTopic(topicName);
        wsManager.sendMessage(new Gson().toJson(reqModel1));
        // isAlreadySubed = true;
    }

    /**
     * 取消订阅 webscoket
     */
    private void unsub(String marketName) {
        if (wsManager.getCurrentStatus() == WsStatus.CONNECTED) {
            ReqModel reqModel1 = new ReqModel();
            reqModel1.setType("unsub");
            reqModel1.setTopic(marketName);
            wsManager.sendMessage(new Gson().toJson(reqModel1));
//            if (marketName.equals(getMarketName())) {
//                isAlreadySubed = false;
//            }
        }
    }

    private void sendPong() {
        ReqModel reqModel = new ReqModel();
        reqModel.setType("pong");
        wsManager.sendMessage(new Gson().toJson(reqModel));
    }


    /**
     * 处理webscoket 数据
     */
    private void handleResult(String marketResult) {
        if (!isVisible()) {
            return;
        }
        Gson gson = new Gson();
        TradeCurrentTotal currentTotal = null;
        try {
            currentTotal = gson.fromJson(marketResult, new TypeToken<TradeCurrentTotal>() {
            }.getType());
        } catch (Exception ignore) {
        }
        if (currentTotal != null && !currentTotal.getType().equals("unsub")) {
            if (currentTotal.getTopic() != null && !currentTotal.getTopic().equals(topicName)) {
                unsub(currentTotal.getTopic());
            }
        }

        if (currentTotal != null && currentTotal.getType().equals("ping")) {
            //发送pong
            sendPong();
        }
        if (currentTotal != null && currentTotal.getTick() != null) {

            rateCny = currentTotal.getTick().getScb_to_cny();//汇率
            tvNewestPrice.setText(currentTotal.getTick().getLast_price());//最新价
            double change = currentTotal.getTick().getChange() == null ? 0 : currentTotal.getTick().getChange();
            tvNewestPrice.setTextColor(change > 0 ? ContextCompat.getColor(mContext, R.color._09C173) : change < 0 ?
                    ContextCompat.getColor(mContext, R.color._F95A54) : ContextCompat.getColor(mContext, R.color._7e8da6));
            tvNewestPrice.setCompoundDrawablesRelativeWithIntrinsicBounds(change > 0 ? R.mipmap.ic_trade_up : change < 0 ? R.mipmap.ic_trade_down : 0,
                    0, 0, 0);


            if ((isFirstSetPrice && !TextUtils.isEmpty(currentTotal.getTick().getLast_price()))) {
                etPrice.setText(currentTotal.getTick().getLast_price());
                //etPrice.setSelection(etPrice.getText().toString().length());
                isFirstSetPrice = !isFirstSetPrice;
            }
            if (isReselectPrice && !TextUtils.isEmpty(currentTotal.getTick().getLast_price())) {
                etPrice.setText(currentTotal.getTick().getLast_price());
                //etPrice.setSelection(etPrice.getText().toString().length());
                isReselectPrice = !isReselectPrice;
            }
            if (currentTotal.getTopic() != null) {
                topicName = currentTotal.getTopic();
                // isAlreadySubed = marketName.equals(getMarketName());
            }
            if (currentTotal.getTick().getBids() != null) {
                tradeBuyList.clear();
                tradeBuyList.addAll(currentTotal.getTick().getBids());
            }
            if (currentTotal.getTick().getAsks() != null) {
                tradeSellList.clear();
                tradeSellList.addAll(currentTotal.getTick().getAsks());
            }
        }

        mSellAdapter.notifyDataSetChanged();
        mBuyAdapter.notifyDataSetChanged();

    }


    //----------------------------------------------event-------------------------------------

    @Subscriber
    void clearMsgNum(BaseEvent event) {
       /* if (event.getCode() == BaseEvent.EventCode.CLEAR_MSG) {
            badgeView.setBadgeNumber(0);
        }*/
    }

    @Subscriber
    void updateMsgNum(BaseEvent event) {
       /* if (event.getCode() == BaseEvent.EventCode.MSG_NUM) {
            HashMap<String, Integer> map = (HashMap<String, Integer>) event.getData();
            int num = 0;
            for (Integer integer : map.values()) {
                num += integer;
            }
            badgeView.setBadgeNumber(num);
        }*/
    }


    @Subscriber
    public void onSelectTradeType(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.TRADE_TYPE) {
            TradeParams tradeParams = (TradeParams) event.getData();
            tradeType = tradeParams.getTradeType();
            currentTitle = tradeParams.getTradeName();
            isReselectPrice = true;
            getMarketName();
            refreshData();
            updateTradeType();
            if (tradeType == TYPE_BUY) {
                rbBuyIn.setChecked(true);
            } else {
                rbSellOut.setChecked(true);
            }

        }

    }


}
